package com.titanrise.crm.common.utils;

import com.titanrise.crm.common.enums.LogEffect;
import com.titanrise.crm.environment.menu.MenuAdapter;
import com.titanrise.crm.environment.orm.JdbcManager;
import com.titanrise.crm.environment.ioc.SingletonPoolUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.UUID;
import java.util.function.Function;

/**
 * @Description:
 * @Author: pront
 * @Time:2024-11-02 14:56
 */
public class ProjectUtil {
    public static <T> T getLine(String message, Function<String, Either<String, T>> fn) {
        Console.print(message, LogEffect.GREEN);
        String line = MenuAdapter.scanner.nextLine();
        Either<String, T> res = fn.apply(line);

        if (res.isLeft()) {
            Console.println(res.getLeft(), LogEffect.RED);
            return ProjectUtil.getLine(message, fn);
        } else {
            return res.getRight();
        }
    }

    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = SingletonPoolUtil.getBean(JdbcManager.class).getConnection();
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
